<template>
  <div class="reviews-management">
    <!-- 页面头部 -->
    <div class="page-header">
      <div class="header-content">
        <h1>评价管理</h1>
        <p>管理客户评价，及时回复提升服务质量</p>
      </div>
      <div class="header-actions">
        <el-button @click="refreshReviews" :loading="refreshing">
          <el-icon><Refresh /></el-icon>
          刷新数据
        </el-button>
      </div>
    </div>

    <!-- 评价统计 -->
    <el-row :gutter="20" class="stats-section">
      <el-col :span="6">
        <el-card class="stat-card good">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Star /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ reviewStats.good }}</div>
              <div class="stat-label">好评</div>
              <div class="stat-rate">{{ ((reviewStats.good / reviewStats.total) * 100).toFixed(1) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card medium">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Warning /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ reviewStats.medium }}</div>
              <div class="stat-label">中评</div>
              <div class="stat-rate">{{ ((reviewStats.medium / reviewStats.total) * 100).toFixed(1) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card bad">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><Close /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ reviewStats.bad }}</div>
              <div class="stat-label">差评</div>
              <div class="stat-rate">{{ ((reviewStats.bad / reviewStats.total) * 100).toFixed(1) }}%</div>
            </div>
          </div>
        </el-card>
      </el-col>
      <el-col :span="6">
        <el-card class="stat-card total">
          <div class="stat-content">
            <div class="stat-icon">
              <el-icon><List /></el-icon>
            </div>
            <div class="stat-info">
              <div class="stat-value">{{ reviewStats.total }}</div>
              <div class="stat-label">总评价</div>
              <div class="stat-rate">平均{{ reviewStats.avgRating }}分</div>
            </div>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 评价列表 -->
    <el-card class="reviews-list-card">
      <template #header>
        <div class="card-header">
          <span>客户评价</span>
          <div class="header-filters">
            <el-select v-model="filterRating" placeholder="评分筛选" style="width: 120px; margin-right: 10px;">
              <el-option label="全部" value="" />
              <el-option label="5星好评" value="5" />
              <el-option label="4星好评" value="4" />
              <el-option label="3星中评" value="3" />
              <el-option label="2星差评" value="2" />
              <el-option label="1星差评" value="1" />
            </el-select>
            <el-select v-model="filterReply" placeholder="回复状态" style="width: 120px;">
              <el-option label="全部" value="" />
              <el-option label="已回复" value="replied" />
              <el-option label="待回复" value="pending" />
            </el-select>
          </div>
        </div>
      </template>

      <div class="reviews-grid">
        <div
          v-for="review in filteredReviews"
          :key="review.id"
          class="review-card"
          :class="getReviewClass(review.rating)"
        >
          <div class="review-header">
            <div class="customer-info">
              <div class="customer-avatar">
                <el-icon><User /></el-icon>
              </div>
              <div class="customer-details">
                <div class="customer-name">{{ review.customerName }}</div>
                <div class="review-time">{{ review.createTime }}</div>
              </div>
            </div>
            <div class="review-rating">
              <el-rate v-model="review.rating" disabled size="small" />
              <span class="rating-text">{{ getRatingText(review.rating) }}</span>
            </div>
          </div>

          <div class="review-content">
            <div class="service-info">
              <span class="service-name">{{ review.serviceName }}</span>
              <span class="order-number">订单号：{{ review.orderNumber }}</span>
            </div>
            <div class="review-text">{{ review.content }}</div>

            <div v-if="review.images && review.images.length > 0" class="review-images">
              <div v-for="(image, index) in review.images" :key="index" class="image-item">
                <el-image
                  :src="image"
                  :preview-src-list="review.images"
                  fit="cover"
                  style="width: 60px; height: 60px; border-radius: 4px;"
                />
              </div>
            </div>
          </div>

          <div v-if="review.reply" class="review-reply">
            <div class="reply-header">
              <el-icon><ChatDotRound /></el-icon>
              <span>商家回复</span>
              <span class="reply-time">{{ review.replyTime }}</span>
            </div>
            <div class="reply-content">{{ review.reply }}</div>
          </div>

          <div class="review-actions">
            <el-button
              v-if="!review.reply"
              size="small"
              type="primary"
              @click="showReplyDialog(review)"
            >
              回复
            </el-button>
            <el-button
              v-else
              size="small"
              @click="showReplyDialog(review)"
            >
              修改回复
            </el-button>
            <el-button
              v-if="review.rating <= 2"
              size="small"
              type="warning"
              @click="appealReview(review)"
            >
              申诉
            </el-button>
            <el-button
              size="small"
              type="info"
              @click="viewOrderDetail(review)"
            >
              查看订单
            </el-button>
          </div>
        </div>
      </div>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="totalReviews"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  Refresh,
  Star,
  Warning,
  Close,
  List,
  User,
  ChatDotRound
} from '@element-plus/icons-vue'
import { getReviewStats, getReviewsList, replyReview, appealReview as apiAppealReview } from '@/api/reviews'

const router = useRouter()
const refreshing = ref(false)
const filterRating = ref('')
const filterReply = ref('')
const currentPage = ref(1)
const pageSize = ref(10)
const totalReviews = ref(0)

// 评价统计
const reviewStats = reactive({
  good: 0,
  medium: 0,
  bad: 0,
  total: 0,
  avgRating: 0
})

// 评价列表
const reviews = ref([])

// 计算属性
const filteredReviews = computed(() => {
  return reviews.value.filter(review => {
    const ratingMatch = !filterRating.value || review.rating.toString() === filterRating.value
    const replyMatch = !filterReply.value ||
      (filterReply.value === 'replied' && review.reply) ||
      (filterReply.value === 'pending' && !review.reply)
    return ratingMatch && replyMatch
  })
})

// 获取评价统计数据
const fetchReviewStats = async () => {
  try {
    const response = await getReviewStats()
    if (response.code === 200) {
      const data = response.data
      reviewStats.good = data.good || 0
      reviewStats.medium = data.medium || 0
      reviewStats.bad = data.bad || 0
      reviewStats.total = data.total || 0
      reviewStats.avgRating = data.avgScore || 0
    } else {
      throw new Error(response.message || '获取评价统计失败')
    }
  } catch (error) {
    console.error('获取评价统计失败:', error)
    ElMessage.error(error.message || '获取评价统计失败')
  }
}

// 获取评价列表数据
const fetchReviewsList = async () => {
  try {
    const params = {
      page: currentPage.value - 1,
      size: pageSize.value,
      rating: filterRating.value || undefined
    }

    const response = await getReviewsList(params)
    if (response.code === 200) {
      reviews.value = response.data.records || response.data || []
      totalReviews.value = response.data.total || reviews.value.length
    } else {
      throw new Error(response.message || '获取评价列表失败')
    }
  } catch (error) {
    console.error('获取评价列表失败:', error)
    ElMessage.error(error.message || '获取评价列表失败')
    reviews.value = []
    totalReviews.value = 0
  }
}

// 方法
const refreshReviews = async () => {
  refreshing.value = true
  try {
    await fetchReviewStats()
    await fetchReviewsList()
    ElMessage.success('数据已刷新')
  } catch (error) {
    console.error('刷新数据失败:', error)
    ElMessage.error('刷新数据失败')
  } finally {
    refreshing.value = false
  }
}

const getReviewClass = (rating) => {
  if (rating >= 4) return 'review-good'
  if (rating >= 3) return 'review-medium'
  return 'review-bad'
}

const getRatingText = (rating) => {
  if (rating === 5) return '非常满意'
  if (rating === 4) return '满意'
  if (rating === 3) return '一般'
  if (rating === 2) return '不满意'
  return '非常不满意'
}

const showReplyDialog = (review) => {
  ElMessageBox.prompt(
    `回复 ${review.customerName} 的评价`,
    '商家回复',
    {
      confirmButtonText: '发送回复',
      cancelButtonText: '取消',
      inputPlaceholder: '请输入您的回复内容...',
      inputValue: review.reply,
      inputValidator: (value) => {
        if (!value || value.trim().length === 0) {
          return '回复内容不能为空'
        }
        if (value.length > 200) {
          return '回复内容不能超过200字'
        }
        return true
      }
    }
  ).then(async ({ value }) => {
    try {
      const response = await replyReview(review.id, {
        content: value
      })

      if (response.code === 200) {
        review.reply = value
        review.replyTime = new Date().toLocaleString()
        ElMessage.success('回复发送成功')
        await fetchReviewsList() // 刷新列表
      } else {
        throw new Error(response.message || '回复发送失败')
      }
    } catch (error) {
      console.error('回复发送失败:', error)
      ElMessage.error(error.message || '回复发送失败')
    }
  }).catch(() => {
    ElMessage.info('已取消回复')
  })
}

const appealReview = (review) => {
  ElMessageBox.prompt(
    `确认对 ${review.customerName} 的评价进行申诉？\n\n请输入申诉理由：`,
    '评价申诉',
    {
      confirmButtonText: '提交申诉',
      cancelButtonText: '取消',
      type: 'warning',
      inputPlaceholder: '请输入申诉理由',
      inputValidator: (value) => {
        if (!value || value.trim().length === 0) {
          return '请输入申诉理由'
        }
        if (value.length < 10) {
          return '申诉理由至少10个字符'
        }
        return true
      }
    }
  ).then(async ({ value }) => {
    try {
      const response = await apiAppealReview(review.id, {
        reason: value,
        reviewContent: review.content,
        rating: review.rating
      })

      if (response.code === 200) {
        ElMessage.success('申诉已提交，平台将在1-3个工作日内处理')
        await fetchReviewsList() // 刷新列表
      } else {
        throw new Error(response.message || '申诉提交失败')
      }
    } catch (error) {
      console.error('申诉提交失败:', error)
      ElMessage.error(error.message || '申诉提交失败')
    }
  }).catch(() => {
    ElMessage.info('已取消申诉')
  })
}

const viewOrderDetail = (review) => {
  ElMessage.info(`查看订单详情：${review.orderNumber}`)
  // 这里可以跳转到订单详情页面
  // router.push(`/main/orders/${review.orderId}`)
}

const handleSizeChange = (val) => {
  pageSize.value = val
  currentPage.value = 1
  fetchReviewsList()
}

const handleCurrentChange = (val) => {
  currentPage.value = val
  fetchReviewsList()
}

const goBack = () => {
  router.push('/main/dashboard')
}

const testFunction = () => {
  ElMessage.success('评价管理功能正常')
}

onMounted(async () => {
  console.log('评价管理页面已加载')
  await fetchReviewStats()
  await fetchReviewsList()
})
</script>

<style scoped>
.reviews-management {
  padding: 20px;
  background: #f5f7fa;
  min-height: calc(100vh - 120px);
}

/* 页面头部 */
.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-end;
  margin-bottom: 20px;
  padding: 20px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.header-content h1 {
  margin: 0 0 8px 0;
  font-size: 24px;
  color: #1f2937;
}

.header-content p {
  margin: 0;
  color: #6b7280;
  font-size: 14px;
}

/* 统计区域 */
.stats-section {
  margin-bottom: 20px;
}

.stat-card {
  border-radius: 12px;
  border: none;
  transition: all 0.3s ease;
}

.stat-card:hover {
  transform: translateY(-2px);
  box-shadow: 0 8px 25px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 20px;
}

.stat-icon {
  width: 60px;
  height: 60px;
  border-radius: 12px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-card.good .stat-icon {
  background: linear-gradient(135deg, #10b981, #059669);
}

.stat-card.medium .stat-icon {
  background: linear-gradient(135deg, #f59e0b, #d97706);
}

.stat-card.bad .stat-icon {
  background: linear-gradient(135deg, #ef4444, #dc2626);
}

.stat-card.total .stat-icon {
  background: linear-gradient(135deg, #3b82f6, #1d4ed8);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 28px;
  font-weight: bold;
  color: #1f2937;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #6b7280;
  margin-bottom: 4px;
}

.stat-rate {
  font-size: 12px;
  color: #9ca3af;
}

/* 评价列表 */
.reviews-list-card {
  border-radius: 12px;
  border: none;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-filters {
  display: flex;
  align-items: center;
}

.reviews-grid {
  display: grid;
  grid-template-columns: 1fr;
  gap: 16px;
  padding: 10px 0;
}

.review-card {
  border: 1px solid #e5e7eb;
  border-radius: 12px;
  padding: 20px;
  background: white;
  transition: all 0.3s ease;
}

.review-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
  transform: translateY(-1px);
}

.review-card.review-good {
  border-left: 4px solid #10b981;
}

.review-card.review-medium {
  border-left: 4px solid #f59e0b;
}

.review-card.review-bad {
  border-left: 4px solid #ef4444;
}

.review-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.customer-info {
  display: flex;
  align-items: center;
}

.customer-avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  background: #f3f4f6;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 12px;
  color: #6b7280;
}

.customer-details {
  flex: 1;
}

.customer-name {
  font-size: 16px;
  font-weight: 500;
  color: #1f2937;
  margin-bottom: 2px;
}

.review-time {
  font-size: 12px;
  color: #9ca3af;
}

.review-rating {
  text-align: right;
}

.rating-text {
  display: block;
  font-size: 12px;
  color: #6b7280;
  margin-top: 4px;
}

.review-content {
  margin-bottom: 16px;
}

.service-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
  padding: 8px 12px;
  background: #f8fafc;
  border-radius: 6px;
}

.service-name {
  font-size: 14px;
  font-weight: 500;
  color: #374151;
}

.order-number {
  font-size: 12px;
  color: #6b7280;
}

.review-text {
  font-size: 14px;
  color: #374151;
  line-height: 1.6;
  margin-bottom: 12px;
}

.review-images {
  display: flex;
  gap: 8px;
  margin-top: 12px;
}

.review-reply {
  margin-bottom: 16px;
  padding: 12px;
  background: #eff6ff;
  border-radius: 8px;
  border-left: 3px solid #3b82f6;
}

.reply-header {
  display: flex;
  align-items: center;
  margin-bottom: 8px;
  font-size: 13px;
  color: #374151;
  font-weight: 500;
}

.reply-header .el-icon {
  margin-right: 6px;
  color: #3b82f6;
}

.reply-time {
  margin-left: auto;
  color: #6b7280;
  font-weight: normal;
}

.reply-content {
  font-size: 14px;
  color: #374151;
  line-height: 1.5;
}

.review-actions {
  display: flex;
  gap: 8px;
  justify-content: flex-end;
}

/* 分页 */
.pagination-wrapper {
  margin-top: 20px;
  text-align: center;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .reviews-management {
    padding: 10px;
  }

  .page-header {
    flex-direction: column;
    gap: 16px;
    text-align: center;
  }

  .stats-section .el-col {
    margin-bottom: 16px;
  }

  .header-filters {
    flex-direction: column;
    gap: 8px;
  }

  .review-header {
    flex-direction: column;
    align-items: flex-start;
    gap: 12px;
  }

  .review-rating {
    text-align: left;
  }

  .service-info {
    flex-direction: column;
    align-items: flex-start;
    gap: 4px;
  }

  .review-actions {
    flex-wrap: wrap;
  }
}

:deep(.el-card__header) {
  background: #fafbfc;
  border-bottom: 1px solid #e5e7eb;
  border-radius: 12px 12px 0 0;
}

:deep(.el-card__body) {
  padding: 20px;
}

:deep(.stat-card .el-card__body) {
  padding: 0;
}

:deep(.el-rate) {
  height: auto;
}

:deep(.el-rate__item) {
  margin-right: 2px;
}
</style>
